package cn.yunhe.dao.impl;

import cn.yunhe.dao.MemberDao;
import cn.yunhe.model.House;
import cn.yunhe.model.Member;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/*sring注解*/
@Repository(value = "memberDao")
public class MemberDaoImpl extends HibernateDaoSupport implements MemberDao {

    @Autowired
    @Qualifier("sessionFactory")
    public void setSessionFactory111(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }

    @Override
    public boolean insertMember(Member member) {
        getHibernateTemplate().save(member);
        return false;
    }

    @Override
    public boolean updateMember(Member member) {
        getHibernateTemplate().update(member);
        return false;
    }

    @Override
    public boolean deleteMember(Integer mid) {
        getHibernateTemplate().delete(this.getById(mid));
        return false;
    }

    @Override
    public Member getById(Integer mid) {
        Member member=getHibernateTemplate().get(Member.class,mid);
        return member;
    }

    @Override
    public List<Member> searchMember(String hql) {
        List<Member>memberList=getHibernateTemplate().find(hql);
        return memberList;
    }

    @Override
    public List<Member> searchMember(final Member member) {
        List<Member>memberList=getHibernateTemplate().executeFind(new HibernateCallback<List<Member>>() {
            @Override
            public List<Member> doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria=session.createCriteria(House.class);

                if (member!=null){
                    if (member.getMid()>0){
                        criteria.add(Restrictions.eq("mdi",member.getMid()));
                    }
                    if (member.getMstate()>0){
                        criteria.add(Restrictions.eq("mstate",member.getMstate()));
                    }
                    if (member.getMflag()>0){
                        criteria.add(Restrictions.eq("mflag",member.getMflag()));
                    }
                }

                List<Member>memberList1=criteria.list();
                return memberList1;
            }
        });
        return memberList;
    }
}
